package com.lagou.filter;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Monitor {

    //方法名
    private String methodName;

    //请求次数
    private int requestCount;

    //请求消耗到时间 ms
    private List<Long> requestUsedTimeList = new ArrayList<>();

    static Monitor getInstance() {
        final Monitor monitor = new Monitor();
        return monitor;
    }

    //加锁，保证线程安全
    public synchronized void saveRequestInfo (String methodName, Long requestUsedTime) {
        requestCount++;
        requestUsedTimeList.add(requestUsedTime);
        this.methodName = methodName;
    }

    public Long getTP(float tpValue) {
        int round = Math.round(requestCount * tpValue);
        requestUsedTimeList = requestUsedTimeList.stream().sorted((l1, l2) -> l1.intValue() - l2.intValue()).collect(Collectors.toList());
        return requestUsedTimeList.get(round-1);
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public int getRequestCount() {
        return requestCount;
    }

    public void setRequestCount(int requestCount) {
        this.requestCount = requestCount;
    }

    public List<Long> getRequestUsedTimeList() {
        return requestUsedTimeList;
    }

    public void setRequestUsedTimeList(List<Long> requestUsedTimeList) {
        this.requestUsedTimeList = requestUsedTimeList;
    }

}
